package net

import (
	"dgo/goutils/httpfs"
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"net/http"
)

var (
	cmdFileSvr_urlMap utils.GSyncMapGroup
)

type UrlRec struct {
	rootDir string
	handler *httpfs.FileHandler
}

func NewUrlRec() *UrlRec {
	rval := &UrlRec{}
	rval.handler = httpfs.FileServer(nil, 0, nil)
	return rval
}

func (this *UrlRec) SetRootDir(val string) bool {
	if this.handler == nil {
		this.handler = httpfs.FileServer(nil, 0, nil)
	}
	if this.rootDir != val {
		this.rootDir = val
		if len(val) == 0 {
			this.handler.Root = nil
		} else {
			this.handler.Root = http.Dir(this.rootDir)
		}
		return true
	}
	return false
}

/*
*
不推荐使用
*/
type ProjCmdHttpFileSvr struct {
	plugId string
	conf   *wrapper.SuperValue
}

func (this *ProjCmdHttpFileSvr) SetPlugID(val string) {
	this.plugId = val
}

/*
*
url 不注册反注册, 一旦注册后不可以修改

	{
	  "id": "kpl-filesvr",
	  "type": "http.cmd.filesvr",
	  "conf": {
	     "map": [
	       {"url": "/kpl-release/", "path":"/usr/dev/vdb1/kpl/release/"},
	       {"url": "/kpl-res/", "path":"/usr/dev/vdb1/kpl/res/"}
	     ]
	  }
	},
*/
func (this *ProjCmdHttpFileSvr) ReloadConf(conf *wrapper.SuperValue) error {
	umap := conf.ValueByName("map")
	if umap == nil {
		return utils.EUnChangedErr
	}
	umap.Range(func(key string, val *wrapper.SuperValue) bool {
		url := val.StringByName("url", "")

		obj, loaded := cmdFileSvr_urlMap.LoadOrStoreFunc2(url, func() interface{} {
			rval := NewUrlRec()
			return rval
		}, nil)
		rec := obj.(*UrlRec)
		if rec.SetRootDir(val.StringByName("path", "")) {
			utils.Log.InfoTypef("STATE", "文件服务:%s(%s)", url, rec.rootDir)
		}
		if !loaded {
			http.Handle(url, http.StripPrefix(url, rec.handler))
		}
		return true
	})
	return nil
}

func (this *ProjCmdHttpFileSvr) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {

	}
	return
}

func CreateProjCmdHttpFileSvrFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &ProjCmdHttpFileSvr{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.plugId = str
		}
	}
	rval = obj
	return
}
